const mongoose = require('mongoose');
const Router = require('koa-router');
const ArticleRouter = new Router();
const ArticleSchema = mongoose.model('Article');
ArticleRouter.get('/getArticle', async(ctx) => {
  try {
    const { currPage } = ctx.request.query;
    const res = await ArticleSchema.find().skip((currPage - 1) * 10).limit(10).sort({createTime: -1}).exec();
    const total = await ArticleSchema.find().countDocuments().exec();
    ctx.body = {
      code: 200,
      message: '获取成功',
      list: res,
      total
    }
  } catch (error) {
    ctx.body = {
      code: 200,
      message: error,
    }
  }
})
ArticleRouter.post('/addArticle', async(ctx) => {
  try {
    await new ArticleSchema(ctx.request.body).save();
    ctx.body = {
      code: 200,
      message: '新增成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})
ArticleRouter.put('/editArticle', async(ctx) => {
  const { articleId, title, desc } = ctx.request.body;
  try {
    // 这里只可以使用Date.now()，不可以使用Date.now，因为这不是在Schema实例中，所以不会调用
    await ArticleSchema.findByIdAndUpdate(articleId, {$set: { title, desc, createTime: Date.now() }});
    ctx.body = {
      code: 200,
      message: '修改成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})
ArticleRouter.get('/getDetail', async(ctx) => {
  try {
    const { articleId } = ctx.request.query;
    const res = await ArticleSchema.findById(articleId, '_id title desc') 
    ctx.body = {
      code: 200,
      detail: res
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

ArticleRouter.delete('/deleteArticle', async(ctx) => {
  try {
    const { articleId } = ctx.request.query;
    await ArticleSchema.findByIdAndRemove(articleId);
    ctx.body = {
      code: 200,
      message: '删除成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})
module.exports = ArticleRouter;